<?php

namespace app\admin\controller\xilujob;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 企业店铺基本信息
 *
 * @icon fa fa-circle-o
 */
class CompanyProfile extends Backend
{
    protected $relationSearch = true;
    protected $multiFields = ['audit_status','personal_audit_status'];
    protected $searchFields = 'enterpriseinfo.company_name,user.email,user.mobile';
    protected $noNeedRight = ['enterprise_info','personal_info'];
    /**
     * CompanyProfile模型对象
     * @var \app\admin\model\xilujob\CompanyProfile
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilujob\CompanyProfile;
        $this->view->assign("personalAuditStatusList", $this->model->getPersonalAuditStatusList());
        $this->view->assign("auditStatusList", $this->model->getAuditStatusList());

        $industry_category = \app\admin\model\xilujob\IndustryCategory::order('weigh')->column('id,name');
        $this->assign('industry_categories',$industry_category);
        $this->assignconfig('industry_category',$industry_category);

        $scales = \app\admin\model\xilujob\CompanyScale::column('id,name');
        $this->assign('scales', $scales);

        $company_types = \app\admin\model\xilujob\CompanyProperties::order('weigh')->column('id,name');
        $this->assign('company_types', $company_types);

        $siteCities = \app\admin\model\xilujob\SiteCity::order('weigh','desc')->column('city_id,city_name');
        $this->assign('site_cities',$siteCities);

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','enterpriseinfo'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
//                ->each(function ($row){
//                    if($row->user){
//                        $row->user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $row->user->mobile);
//                    }
//                });

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add() {
        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            //$userData['city_id'] = $this->siteCity->city_id;
            $enterpriseData = $this->request->post('row/a');
            $modelData = $this->request->post('model/a');

            if($userData['mobile']) {
                $user = User::where('mobile', $userData['mobile'])->find();
            }
            if(!$user && $userData['email']){
                $user = User::where('email', $userData['email'])->find();
            }
            if(isset($user)){
                $count = $this->model->where('user_id',$user['id'])->count();
                if($count>0){
                    $this->error('当前手机号或邮箱已注册过企业账号');
                }
            }
            Db::startTrans();
            try{
                $company = \app\admin\model\xilujob\XilujobUser::add_user(2, $userData, $enterpriseData, $modelData,$user ?? []);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();
            $this->success();
        }
        return $this->view->fetch();
    }


    public function edit($ids=null) {

        $model = $this->model->get($ids);
        if (!$model) {
            $this->error(__('No Results were found'));
        }
        $model = \app\admin\model\xilujob\CompanyProfile::get($ids);
        $user = $model->user;
        $row = $model->enterpriseinfo;

        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            $enterpriseInfo = $this->request->post('row/a');
            $modelData = $this->request->post('model/a');
            Db::startTrans();
            try{
                $ret = \app\admin\model\xilujob\XilujobUser::edit_user($user->id, 2, $userData, $enterpriseInfo, $modelData);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();

            $this->success();
        }
//        if($user){
//            $user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            if(preg_match("/^1[345789]\d{9}$/", $user->username)){
//                $user->username = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            }
//
//        }
        $this->assign('model', $model);
        $this->assign('row', $row);
        $this->assign('user', $user);

        return $this->fetch();
    }


    public function enterprise_info($ids) {
        if(!$this->auth->check('xilujob/company_profile/index')) {
            $this->error(__('You have no permission'));
        }
        $info = \app\admin\model\xilujob\EnterpriseInfo::get(['company_id'=>$ids]);
        $this->view->assign('row',$info);
        return $this->view->fetch('enterprise');
    }

    public function personal_info($ids) {
        if(!$this->auth->check('xilujob/company_profile/index')) {
            $this->error(__('You have no permission'));
        }
        $info = \app\admin\model\xilujob\EnterpriseInfo::get(['company_id'=>$ids]);
        $this->assign('row',$info);
        return $this->fetch('personal');
    }

    public function multi_info($ids) {
        $ids = $ids ? $ids : $this->request->param("ids");
        $this->model = new \app\admin\model\xilujob\EnterpriseInfo();
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $multiFields = ['daily_resume_action_num','resume_action_num','job_num_limit'];
                $values = array_intersect_key($values, array_flip(is_array($multiFields) ? $multiFields : explode(',', $multiFields)));

                if ($values || $this->auth->isSuperAdmin()) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $this->model->where('company_id', 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
